import axios from 'axios';
import {CacheUtil} from "@/utils/cacheUtil.js";
import cache from "@/plugins/cache.js";
import {Utils} from "@/utils/index.js";
import loginUserStore from "@/stores/modules/loginUser.js";
import {AppSign} from "@/utils/appSign.js";
import {ElMessage as $message} from "element-plus";
import {WhiteList} from "@/common/constant.js";

//是否显示重新登录
export let isReLogin = {show: false};
/**
 * axios 配置
 */
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    withCredentials: true,
    timeout: 80000,
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
        'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
        'Content-Type': 'application/json',
        callSource: import.meta.env.VITE_APP_KEY
    }
});

//请求拦截器
service.interceptors.request.use(
    (config) => {
        // 是否需要设置token
        const isToken = (config.headers || {}).isToken === false;
        // 是否需要防止数据重复保存
        const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
        if (CacheUtil.getToken() && !isToken) {
            config.headers.loginToken = CacheUtil.getToken();
        }
        config.headers.sessionGenerateId = CacheUtil.getSessionGenerateId();
        const timestamp = new Date().getTime();
        config.headers.timestamp = timestamp;
        const randomId = Math.random().toString(36).substring(2, 10);
        config.headers.randomId = randomId;
        config.headers.appSign = AppSign.getAppSign(timestamp, randomId, import.meta.env.VITE_APP_KEY);
        // get请求映射params 参数
        if (config.method === 'get' && config.params) {
            let url = config.url + '?' + Utils.tansParams(config.params);
            url = url.slice(0, -1);
            config.params = {};
            config.url = url;
        }
        if (isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
            const requestObj = {
                url: config.url,
                data:
                    typeof config.data === 'object'
                        ? JSON.stringify(config.data)
                        : config.data,
                time: new Date().getTime()
            };
            const sessionObj = cache.session.getJson('sessionObj');
            if (
                sessionObj === undefined ||
                sessionObj === null ||
                sessionObj === ''
            ) {
                cache.session.setJson('sessionObj', requestObj);
            } else {
                const surl = sessionObj.url; // 请求地址
                const sdata = sessionObj.data; // 请求数据
                const stime = sessionObj.time; // 请求时间
                const interval = 1000; // 间隔时间(ms)，小于此时间视为重复保存
                if (
                    sdata === requestObj.data &&
                    requestObj.time - stime < interval &&
                    surl === requestObj.url
                ) {
                    const message = '数据正在处理,请勿重复保存';
                    console.warn(`[${surl}]: ` + message);
                    return Promise.reject(message);
                } else {
                    cache.session.setJson('sessionObj', requestObj);
                }
            }
        }
        return config;
    },
    error => {
        Promise.reject(error).then();
    }
);

// 响应拦截
service.interceptors.response.use(
    res => {
        const loginUser = loginUserStore();
        const requestUrl = res.config.url;
        const ignore = WhiteList.some(v => requestUrl.indexOf(v) > -1);
        let result = res.data;
        // 二进制数据则直接返回
        if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer' || ignore) {
            return result;
        }
        if (result && result.code && result.code !== 1000) {
            if ([4001, 4002].includes(result.code) > 0) {
                // if (!isReLogin.show) {
                //     isReLogin.show = true;
                //     ElMessageBox.confirm(
                //         '登录状态已过期，您可以继续留在该页面，或者重新登录',
                //         '系统提示',
                //         {
                //             confirmButtonText: '重新登录',
                //             cancelButtonText: '取消',
                //             type: 'warning',
                //         }
                //     ).then(() => {
                //         isReLogin.show = false;
                //         loginUser.logout().then(() => {
                //             location.href = '/login';
                //         });
                //     }).catch(() => {
                //         isReLogin.show = false;
                //     });
                // }
                $message.error('无效的会话，或者会话已过期，请重新登录。');
                setTimeout(() => {
                    loginUser.logout().then(() => {
                       location.href = '/login';
                    });
                }, 4500)
                return Promise.reject('无效的会话，或者会话已过期，请重新登录。');
            } else {
                const message = result.message || '系统接口请求异常';
                $message.error(message);
                return Promise.reject(message);
            }
        } else {
            return result;
        }
    },
    error => {
        let {message} = error;
        if (message === 'Network Error') {
            message = '服务器接口连接异常';
        } else if (message.includes('timeout')) {
            message = '系统接口请求超时';
        } else if (message.includes('Request failed with status code')) {
            message = '系统接口' + message.substring(message.length - 3) + '异常';
        }
        $message.error(message);
    }
);
export default service;